package edu.sandau.app.basic.service.impl;

import edu.sandau.app.basic.domain.DishExample;
import edu.sandau.app.basic.domain.DishWithBLOBs;
import edu.sandau.app.basic.mapper.DishMapper;
import edu.sandau.app.basic.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    
    @Autowired
    private DishMapper dishMapper;
    
    @Override
    public List<DishWithBLOBs> getAllDishes() {
        DishExample example = new DishExample();
        return dishMapper.selectByExampleWithBLOBs(example);
    }
    
    @Override
    public DishWithBLOBs getDishById(Long id) {
        return dishMapper.selectByPrimaryKey(id);
    }
    
    @Override
    @Transactional
    public int addDish(DishWithBLOBs dish) {
        dish.setCreateTime(new Date());
        dish.setUpdateTime(new Date());
        if (dish.getDishStatus() == null) {
            dish.setDishStatus("0"); // 默认状态为正常
        }
        if (dish.getSalesCount() == null) {
            dish.setSalesCount(0); // 默认销量为0
        }
        return dishMapper.insertSelective(dish);
    }
    
    @Override
    @Transactional
    public int updateDish(DishWithBLOBs dish) {
        dish.setUpdateTime(new Date());
        return dishMapper.updateByPrimaryKeySelective(dish);
    }
    
    @Override
    @Transactional
    public int deleteDish(Long id) {
        return dishMapper.deleteByPrimaryKey(id);
    }
    
    @Override
    public List<DishWithBLOBs> getDishesByType(String type) {
        DishExample example = new DishExample();
        example.createCriteria().andDishTypeEqualTo(type);
        return dishMapper.selectByExampleWithBLOBs(example);
    }
    
    @Override
    public List<DishWithBLOBs> getDishesByName(String name) {
        DishExample example = new DishExample();
        example.createCriteria().andDishNameLike("%" + name + "%");
        return dishMapper.selectByExampleWithBLOBs(example);
    }
    
    @Override
    public List<DishWithBLOBs> getAvailableDishes() {
        DishExample example = new DishExample();
        example.createCriteria().andDishStatusEqualTo("0");
        return dishMapper.selectByExampleWithBLOBs(example);
    }
    
    @Override
    @Transactional
    public int increaseSalesCount(Long dishId, Integer quantity) {
        DishWithBLOBs dish = dishMapper.selectByPrimaryKey(dishId);
        if (dish != null) {
            dish.setSalesCount(dish.getSalesCount() + quantity);
            dish.setUpdateTime(new Date());
            return dishMapper.updateByPrimaryKeySelective(dish);
        }
        return 0;
    }
}

